import { INodeStruct } from './types';


export function createTreeFactory<TData>(parentKey: string, id: string, parentId: string, getNodeName: (data: TData) => string) {
    const create = (parentValue: any, datas: TData[]) => {
        let result: INodeStruct<TData>[] = [];
        for (let item of datas) {
            // @ts-ignore
            if (item[parentKey] === parentValue) {
                result.push({
                    // @ts-ignore
                    id: item[id],
                    name: getNodeName(item),
                    checked: false,
                    isOpen: false,
                    data: item,
                    // @ts-ignore
                    children: create(item[id], datas)
                });
            }
        }
        return result;
    }
    return create;
}
/**
 * 
 * @param node 
 * @returns INodeStruct<T>[]
 */
export function flatTree<T>(node: INodeStruct<T> | INodeStruct<T>[]): INodeStruct<T>[] {
    let result: INodeStruct<T>[] = [];
    function travel(data: INodeStruct<T> | INodeStruct<T>[]) {
        if (data instanceof Array) {
            for (let item of data) {
                result.push(item);
                travel(item.children);
            }
        } else {
            result.push(data);
            travel(data.children);
        }
    }
    travel(node);
    return result;
}
export function isFoot<T>(root: INodeStruct<T>, node: INodeStruct<T>) {
    if(root === node) {
        return true;
    } else {
        for(let child of root.children) {
            if(isFoot<T>(child, node) === true) {
                return true;
            }
        }
    }
    return false;
}
export function findRoot<T>(roots: INodeStruct<T>[], node: INodeStruct<T>): INodeStruct<T>|null {
    for(let root of roots) {
        if(isFoot<T>(root, node) === true){
            return root;
        }
    }
    return null;
}

export function findParent<T>(root: INodeStruct<T>, node: INodeStruct<T>): null| INodeStruct<T> {
    console.log(root, node)
    for(let child of root.children) {
        if(child === node) {
            return root;
        } else {
            let temp = findParent<T>(child, node);
            if(temp !== null) {
                return temp;
            } 
        }
    }
    return null;
}